package com.ztom.top100;

/**
 * 环形链表2
 * <p>
 * https://leetcode-cn.com/problems/linked-list-cycle-ii/
 *
 * @author ZhangTao
 */
public class Code51DetectCycle {

    class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }

    public ListNode detectCycle(ListNode head) {
        if (head == null) {
            return null;
        }
        // 快慢指针: 第一次相遇后, fast 指针回到 head 并变为慢指针
        ListNode fast = head;
        ListNode slow = head;

        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
            if (fast == slow) {
                // 第一次相遇
                ListNode p = head;
                while (p != slow) {
                    p = p.next;
                    slow = slow.next;
                }
                return p;
            }
        }
        return null;
    }
}
